package com.ruoyi.common.utils;


import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


@Component
public class AddressUtils {


    public static final String GD_URL = "https://restapi.amap.com/v3/geocode/geo?key=6e673d1e15a949dda845f29d8861624d&address=";
    public static final String BD_URL = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=MlbWGTcovSCcHEVBvft8vSnTi4M1mclF&output=json&coordtype=wgs84ll&location=";


    /**
     * 根据地址获取经纬度信息
     */
    public static String getGeographyInfoByAddress(String address) {
        String result = "";
        try {
            // 把字符串转换为URL请求地址
            URL url = new URL(GD_URL + address);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 连接会话
            connection.connect();
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;

            StringBuilder sb = new StringBuilder();

            // 循环读取流
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            result = sb.toString();

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
        return result;
    }

    /**
     * 根据经纬度获取地址信息
     */
    public static String getGeographyInfoByLongLati(String longLati) {
        String result = "";
        try {
            // 把字符串转换为URL请求地址
            URL url = new URL(BD_URL + longLati);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 连接会话
            connection.connect();
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;

            StringBuilder sb = new StringBuilder();

            // 循环读取流
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            result = sb.toString();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
        return result;

    }
}



